import hashlib
import json
import random
import string
import time
from flask import Flask, make_response, render_template,g,request
from def_sql import get_druglist,insert_drug,insert_cookie
from def_models import DBSession


def ranstr():
    salt = genearteMD5(str(time.time()).join(random.sample(string.ascii_letters + string.digits, 8)))
    return salt


# 生成MD5
def genearteMD5(str):
    # 创建md5对象
    hl = hashlib.md5()

    # Tips
    # 此处必须声明encode
    # 否则报错为：hl.update(str)    Unicode-objects must be encoded before hashing
    hl.update(str.encode(encoding='utf-8'))

    print('MD5加密前为 ：' + str)
    print('MD5加密后为 ：' + hl.hexdigest())
    return (hl.hexdigest())

app=Flask(__name__)

@app.before_request
def setup():
    global session
    session = DBSession()

@app.teardown_request
def after(exception):
    session.close()
    print("close")

#@app.after_request
#def after():
 #   session.close()

#@app.before_request
#def be():
#    g.session=DBSession()

#@app.after_request
#def close_session():
#    g.session.close()



@app.route('/')
def hello_world():
    return render_template("main.html")

@app.route('/drug',methods=["GET","POST"])
def drug():
    if request.cookies.get("w3cshool")==None:
        cookie_1=ranstr()
        insert_cookie(session=session,cookie=cookie_1,ip="127.0.0.1",telephone=15130940858)
        resp = make_response(render_template("drug.html",list=get_druglist(session)))   # 设置响应体
        resp.set_cookie("w3cshool", cookie_1, max_age=3600)            # cookie有效值为3600秒
        return resp
    else:
        print(request.cookies.get("w3cshool"))
        return render_template("drug.html",list=get_druglist(session))

@app.route('/recive',methods=["POST"])
def recive():
    print(request.cookies)
    data = request.get_data()
    print(data.decode("utf-8"))
    insert_drug(session=session,drug=json.loads(data.decode("utf-8")))
    return render_template("drug_insert.html")

@app.route('/delcookie',methods=["GET"])
def delcookie():
    if request.cookies.get("w3cshool")==None:
        cookie_1=ranstr()
        resp = make_response(render_template("drug.html",list=get_druglist(session)))   # 设置响应体
        resp.set_cookie("w3cshool", cookie_1, max_age=3600)            # cookie有效值为3600秒
        return resp
    else:
        resp = make_response(render_template("drug.html",list=get_druglist(session)))   # 设置响应体
        resp.set_cookie("w3cshool", "", max_age=0)
        return resp

@app.route('/build',methods=["GET"])
def build():
    return render_template("test.html")

if __name__=='__main__':
    app.run(host='0.0.0.0',port=80)